package com.example.zjx8969.myapplication

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.util.DisplayMetrics
import android.view.*
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.zjx8969.myapplication.beans.Introduce
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.activity_on_boarding.*
import kotlinx.coroutines.launch

//@Route(path = "/welcome/onBoarding")
class OnBoardingActivity : BaseActivity(), View.OnClickListener {
    private lateinit var adapter: OnBoardingAdapter
    private lateinit var viewPager: RecyclerView
    private lateinit var linearLayoutManager: LinearLayoutManager
    private lateinit var skipBtn: Button
    override fun onCreate(savedInstanceState: Bundle?) {
        val wm = this.getSystemService(WINDOW_SERVICE) as WindowManager
        val displayMetrics = DisplayMetrics()
        wm.defaultDisplay.getRealMetrics(displayMetrics)
        val metrics = resources.displayMetrics
        if (metrics.widthPixels * 1f / metrics.heightPixels > 9f / 16) {
            val decorView = window.decorView
            decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN
        }
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_on_boarding)

        viewPager = findViewById(R.id.onBoardingViewPager)
        linearLayoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        viewPager.layoutManager = linearLayoutManager
        val helper = LinearSnapHelper()
        helper.attachToRecyclerView(viewPager)
        skipBtn = findViewById(R.id.onBoardingSkip)
        skipBtn.setOnClickListener(this)
        adapter = OnBoardingAdapter()
        viewPager.adapter = adapter
        viewPager.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    val position = linearLayoutManager.findFirstCompletelyVisibleItemPosition()
                    for (i in indicator.childCount - 1 downTo 0) {
                        indicator.getChildAt(i).isSelected = position == i
                    }
                    skipBtn.visibility = if (position == indicator.childCount - 1) View.VISIBLE else View.INVISIBLE
                }
            }

        })

        loadData()

    }


    private fun loadData() {
        lifecycleScope.launch {
            loadData<List<Introduce>>(assets, "introduce.json", object : TypeToken<List<Introduce>>() {}.type) {
                adapter.setData(it)
                it?.let { list ->
                    initIndicator(list)
                }
            }
        }

    }

    private fun initIndicator(data: List<Introduce>) {
        val mPointLeftRightMargin = dip2px(indicator.context, 2f)
        val mPointTopBottomMargin = dip2px(indicator.context, 3f)
        val lp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        lp.setMargins(mPointLeftRightMargin, mPointTopBottomMargin, mPointLeftRightMargin, mPointTopBottomMargin)
        lp.gravity = Gravity.CENTER_HORIZONTAL or Gravity.CENTER_VERTICAL
        var imageView: ImageView
        for (i in data.indices) {
            imageView = ImageView(indicator.context)
            imageView.layoutParams = lp
            if (i == 0) imageView.isSelected = true
            imageView.setImageResource(R.drawable.bga_banner_selector_point_hollow)
            indicator.addView(imageView)
        }
        //        linearLayout.setBackgroundResource(R.drawable.ic_homebanner_shade_bottom);
    }

    fun dip2px(context: Context, dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    private inner class OnBoardingAdapter : RecyclerView.Adapter<ViewHolder>() {
        val ratio: Float
        val width: Int = resources.displayMetrics.widthPixels
        val bgHeight: Int
        private var data: List<Introduce>? = null
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_on_boarding, parent, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val introduce = data!![position]
            val localeLanguage =  /*"ru";*/LanguageUtil.getLocaleLanguage()
            holder.title.text = introduce.title[localeLanguage]
            holder.desc.text = introduce.description[localeLanguage]
            Glide.with(this@OnBoardingActivity).asBitmap().load("file:///android_asset/" + introduce.image[0]).override(width, bgHeight)
                    .fitCenter().into(holder.imageViewBg)
            (ratio * introduce.imageSize[11]).toInt()
 
            Glide.with(this@OnBoardingActivity).asBitmap().load("file:///android_asset/" + introduce.image[5]) /*.fitCenter()*/.override(width, (ratio * introduce.imageSize[11]).toInt()).diskCacheStrategy(DiskCacheStrategy.NONE).into(holder.imageViewCenter)

//            setupCenterView(holder.imageViewCenter, position);
            setupMarginTopView(holder.imageViewUpRight, position)
            loadImage(holder.imageViewUpCenter, introduce, 1)
            loadImage(holder.imageViewUpRight, introduce, 2)
            loadImage(holder.imageViewLeft, introduce, 3)
            loadImage(holder.imageViewRight, introduce, 4)
            if (introduce.image.size == 7 && holder.imageViewDark != null) {
                loadImage(holder.imageViewDark, introduce, 6)
            }
            //            loadImage(holder.imageViewCenter, introduce.image[5]);
        }

        private fun loadImage(imageView: ImageView?, introduce: Introduce?, index: Int) {
            if (introduce == null || introduce.image.size <= index) return
            val url = introduce.image[index]
            if (TextUtils.isEmpty(url)) return
            val width = (ratio * introduce.imageSize[index * 2]).toInt()
            val height = (ratio * introduce.imageSize[index * 2 + 1]).toInt()
            Glide.with(this@OnBoardingActivity).asBitmap().load("file:///android_asset/$url") /*.centerInside()*/.override(width, height).into(imageView!!)
        }

        private fun setupMarginTopView(imageViewCenter: ImageView, position: Int) {
            val isArtist = position == data!!.size - 1
            val layoutParams = imageViewCenter.layoutParams as ConstraintLayout.LayoutParams
            if (isArtist) {
                layoutParams.setMargins(0, dip2px(this@OnBoardingActivity, 125f), 0, 0)
            } else {
                layoutParams.setMargins(0, dip2px(this@OnBoardingActivity, 60f), 0, 0)
            }
            imageViewCenter.layoutParams = layoutParams
        }

        override fun getItemCount(): Int {
            return if (data == null) 0 else data!!.size
        }

        fun setData(data: List<Introduce>?) {
            this.data = data
            notifyDataSetChanged()
        }

        init {
            bgHeight = width * 2688 / 1242
            ratio = width / 1242f
        }
    }

    override fun onClick(v: View) {
        if (v.id == R.id.onBoardingSkip) {

//            compressImage();
//            PreferenceUtil.putBoolean(this, SplashPref.FILE_ACTIVITY_STATED, SplashPref.keyNeedShowOnBoarding, false);
            setResult(Activity.RESULT_OK);
            finish()
        }
    }

    private class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var imageViewBg: ImageView = view.findViewById(R.id.onBoardingImageBg)
        var imageViewCenter: ImageView = view.findViewById(R.id.onBoardingImageCenter)
        var imageViewUpCenter: ImageView = view.findViewById(R.id.onBoardingImageUp1)
        var imageViewUpRight: ImageView = view.findViewById(R.id.onBoardingImageUp2)
        var imageViewLeft: ImageView = view.findViewById(R.id.onBoardingImageLeft)
        var imageViewRight: ImageView = view.findViewById(R.id.onBoardingImageRight)
        var imageViewDark: ImageView? = view.findViewById(R.id.onBoardingImageUp3)
        var title: TextView = view.findViewById(R.id.onBoardingImageTitle)
        var desc: TextView = view.findViewById(R.id.onBoardingImageDesc)

    }

    override fun onBackPressed() {
        finish()
    }
}